package com.aplink.sell_proof.services;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.MethodParams;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.database.table.ClaimDBHelper;
import com.applink.sell_proof.database.table.DistributorDBHelper;
import com.applink.sell_proof.database.table.ProductModelDBHelper;
import com.applink.sell_proof.database.table.ProjectDBHelper;
import com.applink.sell_proof.model.Claim;
import com.applink.sell_proof.model.Distributor;
import com.applink.sell_proof.model.Product;
import com.applink.sell_proof.model.Project;

public class DataSync extends IntentService implements Observer {

	public DataSync() {
		super("DataSync");
		Log.d("DataSync", "Service constructor create");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.d("DataSync", "Service started");

		// get the MethodParams from the intent
		MethodParams mp = (MethodParams) intent.getSerializableExtra("method");
		Methods m = mp.getName();

		switch (m) {
		case updateUserActivity:
//			DataHelper.getInstance().updateUserActivity();
//			AnalyticDBHelper.emptyTable();
			break;
		case projectsSync:

			List<Project> pjs = ProjectDBHelper.getNotUpdatedRecords();

			if (pjs.size() >= 1) {
				// DataHelper.getInstance().addObserver(this);
				DataHelper.getInstance().syncProjectsToServer(pjs);
			}

			break;
		case searchProductModel:

			List<Product> pds = ProductModelDBHelper.searchProduct("");

			if (pds.size() > 0)
				return;

			DataHelper.getInstance().searchProductModelOnline("");
			break;
		case claimsSync:

			List<Claim> cls = ClaimDBHelper.getNotUpdatedRecords();

			if (cls.size() == 1) {
				// DataHelper.getInstance().addObserver(this);
				DataHelper.getInstance().syncClaimToServer(cls.get(0));
			}

			break;
		case getAllDistributor:

			List<Distributor> ds = DistributorDBHelper.getAllDistributor();

			if (ds.size() > 0)
				return;
			
			DataHelper.getInstance().getAllDistributor();

			break;
		default:
			break;
		}
	}

	public static void doSync(MethodParams method) {
		Log.d("DataSync", "Service initializing");

		Intent msgIntent = new Intent(EMarketing.getInstance(), DataSync.class);

		// store method params to the Intent
		msgIntent.putExtra("method", method);

		EMarketing.getInstance().startService(msgIntent);
	}

	@Override
	public void update(Observable observable, Object data) {
	}
}
